package cn.edu.hbwe.book.servlet.book;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.hbwe.book.entity.Book;
import cn.edu.hbwe.book.exception.FindBookByIdException;
import cn.edu.hbwe.book.service.BookService;

/**
 * Servlet implementation class AddCarServlet
 */
public class AddCarServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 获取添加购物车中的商品id
		String id = request.getParameter("id");
		BookService service = new BookService();
		try {
			Book book = service.findBookById(id);
			//获取sessiion
			HttpSession session = request.getSession();
			//获取购物车
			Map<Book,Integer> cart = (Map<Book, Integer>) session.getAttribute("cart");
			//判断购物车内是否有商品
			if(cart == null) {
				cart = new HashMap<Book, Integer>();
			}
			//添加商品到购物车,首次添加商品
			Integer count = cart.put(book, 1);
			if(count != null) {
				cart.put(book, count+1);
			}
			//把商品放到session，跳转到cart.jsp显示商品
			session.setAttribute("cart", cart);
			response.sendRedirect(request.getContextPath()+"/bookweb/cart.jsp");
			
		} catch (FindBookByIdException e) {
			response.getWriter().print(e.getMessage());
		}
	}

}
